//
//  YMLeftTitleView.swift
//  AllClassDemo
//
//  Created by zeng on 2018/3/6.
//  Copyright © 2018年 youmy. All rights reserved.
//

import UIKit

private let kLineColor : (CGFloat, CGFloat, CGFloat) = (230, 230, 230)//0xe6e6e6
private let kBgColor : (CGFloat, CGFloat, CGFloat) = (249, 251, 253)//0xf9fbfd

protocol YMLeftTitleViewDelegate:NSObjectProtocol {
    func titleView(leftTitleView: YMLeftTitleView, didSelectRow:Int, title:String)
}

class YMLeftTitleView: UIView {

    fileprivate var titles : [String]
    
    fileprivate var selRow:Int = 0
    
    var delegate:YMLeftTitleViewDelegate?
    
    lazy var tableView:UITableView = {
        let tableView = UITableView(frame: bounds)
        tableView.backgroundColor = ym_bg_color
        tableView.tableFooterView = UIView()
        tableView.rowHeight = 55
        tableView.separatorColor = ym_seprator_color_1
        tableView.dataSource = self
        tableView.delegate = self
        
        tableView.isScrollEnabled = CGFloat(titles.count) * 55 > bounds.height
        
        tableView.register(UINib.init(nibName: "YMLeftTitleCell", bundle: nil), forCellReuseIdentifier: "cellID")
        
        return tableView
    }()
    
    init(frame: CGRect, titles:[String]) {
        
        self.titles = titles
        
        super.init(frame: frame)
        
        addSubview(tableView)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


extension YMLeftTitleView:UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titles.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath) as! YMLeftTitleCell
        cell.selectionStyle = .none
        cell.titleLbl.text = titles[indexPath.row]
        if selRow == indexPath.row {
            cell.contentView.backgroundColor = .white
            cell.flagV.isHidden = false
        }else{
            cell.contentView.backgroundColor = ym_bg_color
            cell.flagV.isHidden = true
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selRow = indexPath.row
        let cells = tableView.visibleCells
        let cell = tableView.cellForRow(at: indexPath) as! YMLeftTitleCell
        
        for obj in cells {
            let cell = obj as! YMLeftTitleCell
            cell.contentView.backgroundColor = ym_bg_color
            cell.flagV.isHidden = true
        }
        cell.contentView.backgroundColor = .white
        cell.flagV.isHidden = false
        
        delegate?.titleView(leftTitleView: self, didSelectRow: indexPath.row, title: titles[indexPath.row])
    }
}
